# -*- coding: utf-8 -*-
#!/usr/bin/env python
# encoding: utf-8
"""
views.py

Created by 姚 远 on 2010-04-15.
Copyright (c) 2010 knarfytrebil. All rights reserved.
"""
#import from google apps engine
from google.appengine.ext import db
from google.appengine.ext.db import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp \
	import template
#django
from django.utils import simplejson as json
#python library
import urllib2,time,datetime,urllib,string
from datetime import datetime
from datetime import timedelta
#system and so on
import sys,os
import socket
import string
#then we are going to import something else, and this involves with some nasty stuff
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path = [current_dir] + sys.path
#finished adding current path to sys.path
from app import lib
#imported my library
class AdminBlogHandler(webapp.RequestHandler):
	def get(self,req_id):
		if req_id == "board":
			def_title('cn')
			forum_title_text = "最新日志"
			forum_time_text = "最后更新"
			id = ""
			titan = "回去论坛/掲示板に戻る/Go back to forum"
			languages = "<a href = '#'>道可道非常道</a>"
			script = "js/forum-cn.js"
			cursor.execute ("""
					SELECT title, time, id 
					FROM cloud_titan
					ORDER BY time DESC
					LIMIT 20
					""")
			rows = cursor.fetchall()
			topics = []
			file = "cloud/titan.html"
			for row in rows:
				topics.append("<a href = '/titan/contents?id="+ str(row[2]) + "'>"+ str(row[0]) + "</a>" + "<li>" + str(row[1]) + "</li>")
		if req_id == "contents":
			file = "cloud/titan-contents.html"
			req_id = str(self.get_argument('id'))
			forum_title_text = ""
			forum_time_text = "Last updated"
			titan = "Home／ホーム"
			languages = "<a href = '/forum/contents?lang=jp&id=" + req_id + "'>日本語</a><a href = '/forum/contents?lang=en&id="+ req_id + "'>English</a>"
			script = "js/contents-cn.js"
			cursor.execute ("""
					SELECT body, time
					FROM cloud_titan
					WHERE id = %s
					""",req_id)
			piece = cursor.fetchone()
			cursor.execute ("""
					SELECT body, time 
					FROM cloud_titan_replies
					WHERE topic_id = %s
					ORDER BY time DESC
					""",req_id)
			rows = cursor.fetchall()
			topics = []
			id = req_id
			topics.append("<a>" + str(piece[0]) + "<em>" + str(piece[1]) + "</em>""</a>")
			for row in rows:
				topics.append("<a>"+ str(row[0]) + "<em>" + str(row[1]) + "</em>""</a>")
		self.render(file,
			#Local Items
			id = id,
			forum_time_text = forum_time_text,
			forum_title_text = forum_title_text,
			topics = topics,
			url_forum = "/?lang=en",
			titan = titan,
			#Under are all commons
			title = g_title,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			home = g_home,
			forum = g_forum,
			translate =  g_translate,
			fuckml = g_fuckml,
			chat = g_chat,
			script = script,
			languages = languages)
class InfoHandler(webapp.RequestHandler):
	def post(self, data):
		#the correct way of getting a remote ip. and handle that later.
		client_ip = str(self.request.remote_ip)
		uid = gen_unique_id(client_ip)
		if data == "":
			lang = self.get_argument("lang").encode("utf-8","ignore")
			title = self.get_argument("title").encode("utf-8","ignore")
			body = self.get_argument("body").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_forum
						ORDER BY id DESC
						LIMIT 1""")
			row = cursor.fetchone()
			last_forum_id = int(row[0]) + 1
			cursor.execute("""INSERT INTO cloud_forum
						VALUES (%s, %s, %s, %s,CURRENT_TIMESTAMP,%s)
						""", (title, body,last_forum_id,lang,uid))
			output = "Post Success!"
		elif data == "titan":
			title = self.get_argument("title").encode("utf-8","ignore")
			lang = title[5:7]
			body = self.get_argument("body").encode("utf-8","ignore")
			if (body[:17] <> "password:ododlaed") or (title[:4] <> "lang"):
				output = "休想发布任何消息！STAY WHILE YOU ENJOY YOUR LAST MOMENTS!!"
			else:
				cursor.execute("""
						SELECT id FROM cloud_titan
						ORDER BY id DESC
						LIMIT 1""")
				row = cursor.fetchone()
				last_titan_id = int(row[0]) + 1
				cursor.execute("""INSERT INTO cloud_titan
							VALUES (%s, %s, %s, %s,CURRENT_TIMESTAMP)
							""", (title[7:], body[17:],last_titan_id,lang,))
				output = "我果然是天才！居然不知道你是谁！"
		elif data == "reply":
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_replies
						WHERE topic_id = %s
						ORDER BY id DESC
						LIMIT 1""",(id))
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			cursor.execute("""INSERT INTO cloud_replies
						VALUES (%s, %s,CURRENT_TIMESTAMP, %s, %s)
						""", (id, body,last_titan_id,uid))
			cursor.execute("""
							UPDATE cloud_forum
							SET time = CURRENT_TIMESTAMP
							WHERE id = %s
							""",id)
			output = "Post Success!"
		elif data == "replytitan":
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_titan_replies
						WHERE topic_id = %s
						ORDER BY id DESC
						LIMIT 1""",(id))
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			cursor.execute("""INSERT INTO cloud_titan_replies
						VALUES (%s, %s,CURRENT_TIMESTAMP, %s, %s)
						""", (id, body,last_titan_id,uid))
			output = "Post Success!"
		elif (data == "fml") or (data == "translate"):
			db_table = "cloud_" + str(data)
			lang = self.get_argument("lang").encode("utf-8","ignore")
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			print db_table	
			if data == "fml":	
				cursor.execute("""SELECT id FROM cloud_fml ORDER BY id DESC LIMIT 1""")
			else:
				cursor.execute("""SELECT id FROM cloud_translate ORDER BY id DESC LIMIT 1""")	
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			if data == "fml":	
				cursor.execute("""INSERT INTO cloud_fml
						VALUES (%s, CURRENT_TIMESTAMP,%s, 0, %s,%s)
						""", (body,last_titan_id,lang,uid)) 
			else:
				cursor.execute("""INSERT INTO cloud_translate
						VALUES (%s, CURRENT_TIMESTAMP,%s, 0, %s,%s)
						""",(body,last_titan_id,lang,uid))	
			output = "Post Success!"
		self.write(output)
class ForumHandler(webapp.RequestHandler):
	def get(self):
		css = ""
		req_lang = str(self.request.get('lang'))
		lib.def_title(req_lang)
		if req_lang == "en":
			forum_title_text = "All Topics:"
			forum_time_text = "Unique ID  |  Last updated"
			titan = "titan's blog<span> }</span><p>Sticky Link</p><br><em>the official blog of the website</em></br>"
		elif req_lang == "jp":
			forum_title_text = "スレッド："
			forum_time_text = "ユニックID  |  最新更新"
			titan = "タイタンのブログ<span> }</span><p>固定リンク</p><br><em>公式サイトボログ</em></br>"
		languages = "<a href = '/forum/board?lang=jp'>日本語</a><a href = '/forum/board?lang=en'>English</a>"
		script = "js/forum-"+ str(req_lang) + ".js"
		topics = []
		id = ""
		file = "cloud/forum.html"
		
		self.response.out.write(template.render(path, values))
		self.render(file,
			#Local Items
			forum_time_text = forum_time_text,
			forum_title_text = forum_title_text,
			topics = topics,
			titan = titan,
			id = id,
			#Under are all commons
			css = css,
			title = g_title,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			home = g_home,
			forum = g_forum,
			translate =  g_translate,
			fuckml = g_fuckml,
			chat = g_chat,
			script = script,
			languages = languages,
			url_home = g_url_home,
			url_forum = g_url_forum,
			url_translate = g_url_translate,
			url_chat = g_url_chat,
			url_fuckml = g_url_fuckml)

class IndexHandler(webapp.RequestHandler):
	from models import Blog,Topics
	def get(self):
		req_lang = self.request.get('lang')
		################
		##Redirecting users to the top page
		################
		if req_lang == "":
			path = lib.genpath('/html/templates','top.html')
			self.response.out.write(template.render(path,""))
			return
		#end of that
		##initiating 
		title = ""
		script = "/../static/js/hp-"+ str(req_lang) + ".js"
		infolst = lib.def_title(str(req_lang))
		indexlst = lib.def_index(str(req_lang))
		#########
		#Load
		##############
		blogs = []
		m = [[],[],[]]
		#End of the load
		#############################
		## Start 
		#############################
		query = db.GqlQuery('SELECT * FROM Blog ORDER BY updated DESC')
		rows = query.fetch(10)
		if rows == []:
			blogs = ["N/A"]
		else:
			for row in rows:
				mon = str(row[1])[5:7]
				tm = str(row[1])[-8:]
				dayy = str(row[1])[-11:-8]
				dic_mon = {'01':'Jan','02':'Feb','03':'Mar','04':'Apr','05':'May',
					'06':'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov',
					'12':'Dec'}
				mon = dic_mon[mon]
				blogs.append( str(row[0]) + "<em>{</em><li>" + str(row[2]) + 
					"</li>" + "<li><span id ='mon'>" + mon  + "<span id ='dayy'>" + dayy + "</span></span><span id ='tm'>"+ tm + "</span></li><p><em>}</em>" + 
					"<a href = 'http://211.6.189.194:8888/titan/contents?id=" + str(row[3])
					+ "'>" + reply_text + "</a><em>{</em></p>")
			row = ""
			query = ""
		#######################
		#Finishing unload
		#and yet starting again
		#######################
		n = ['contents','translate','fuckml']
		for i in range (1,4):
			query = db.GqlQuery('SELECT * FROM Topics WHERE kind_id = :1 AND depth = 0 ORDER BY updated DESC',i)
			rows = query.fetch(10)
			for row in rows:
				m[i-1].append( "<a href = 'http://211.6.189.194:8888/forum/"+ n[i-1] + "?id=" + str(row[1]) + "&lang=" + req_lang 
					+ "'>" + str(row[0][:35]) + " ...</a>")
			rows = ""
			query = ""
		##############################
		###end of loading all the shit
		##############################
		path = lib.genpath('/html/templates/','index.html')
		values = { 'translation_heads':m[1],'forum_heads':m[0],
					'fml_heads':m[2],'headblock':indexlst[7],
					'title':infolst[1][0],'blogs':blogs,
					'cloud_info':infolst[1][1],'cloud_slogan':infolst[1][2],
					'languages':indexlst[0],'script':script,
					#urls - Start
					'home':infolst[1][3],'url_home':infolst[0][0],
					'forum':infolst[1][4],'url_forum':infolst[0][1],
					'translate':infolst[1][5],'url_translate':infolst[0][2],
					'fuckml':infolst[1][6],'url_fuckml':infolst[0][4],
					'chat':infolst[1][7],'url_chat':infolst[0][3],
					#urls - End 
					'facebook':indexlst[1],'twitter':indexlst[2],
					'translation':indexlst[3],'self_intro':indexlst[4],
					'fml':indexlst[5] }
		self.response.out.write(template.render(path, values))